package com.kt.service.impl;

import com.kt.pojo.Menu;
import com.kt.mapper.MenuMapper;
import com.kt.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kt.util.AdminUtils;
import io.netty.channel.ConnectTimeoutException;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author KamTeng
 * @since 2021-02-22
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 通过用户ID查询菜单列表
     *
     * @return
     */
    @Override
    public List<Menu> getMenusByAdminId() {
        Integer adminId = AdminUtils.getCurrentAdmin().getId();
        // 如果redis服务未开起，就直接从数据库中获取
        try {
            List<Menu> menus = menuMapper.getMenusByAdminId(adminId);
            return menus;
        }catch (RedisConnectionFailureException e) {
            ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
            // 从redis获取菜单数据
            List<Menu> menus = (List<Menu>) opsForValue.get("menu_" + adminId);
            // 如果为空，就去数据库中获取
            if (CollectionUtils.isEmpty(menus)) {
                menus = menuMapper.getMenusByAdminId(adminId);
                // 将数据设置到redis中
                opsForValue.set("menu_"+adminId, menus);
            }
            return menus;
        }
    }

    /**
     * 根据角色获得菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
